package com.xuliugen.javamybatis.demo.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 获取SqlSession工具类
 * Created by xuliugen on 2017/9/20.
 */
public class SqlSessionUtil {

    /**
     * 获取SqlSessionFactory
     * @return
     * @throws IOException
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        String resource = "conf/mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    /**
     * 获取SqlSession
     * @return
     * @throws IOException
     */
    public static SqlSession getSqlSession() {
        return getSqlSessionFactory().openSession();
    }
}
